#! /usr/bin/env python
# -*- coding: utf-8 -*-

import re
import os
import time
import random

import FileHostProtoType


class f4sitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, id, link, encrypt_name='', server_name=''): 
        FileHostProtoType.HostItem.__init__(self, name, type, id, link, encrypt_name, server_name)
        
class file4sharing(FileHostProtoType.FileHostProcess):
    def __init__(self,user,pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "file4sharing"
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self._ftppwd = ''
        
    def loginFileHost(self,loginurl,logindata):
        return FileHostProtoType.FileHostProcess.loginFileHost(self, loginurl, logindata)

    def login(self):
        '''
        login to file4sharing
        return opener object which includes cookies
        '''
        self.generateOpener()
        if self.check_cookie():
            return True
        self.fherr.write('login to file4sharing %s/%s...'%(self._user,'*'*len(self._pwd)))
        loginData = {'login' : self._user, \
                'password' : self._pwd,
                'op' : 'login',
                'redirect' : 'http://file4sharing.com/?op=my_account' }
        response = self.loginFileHost("http://file4sharing.com/", loginData)
        # user info can be found in cookie
        if self._user.lower() not in response.lower():
            self.fherr.write("User %s Failed to Login MegaUpload." % self._user)
            return False
        self.fherr.write("User %s logined." % self._user)
        self.islogin = True
        return True
    
    def check_cookie(self):
        return self.islogin
    
    def check_login(self):
        if self.check_cookie():
            return
        self.fherr.write('cookie unavaiable, reLogin...')
        while not self.login():
            time.sleep(5)
    
    def getFileList(self):
        folders = self.getFolderList()
        root = f4sitem('root','/root','0','')
        folders.append(root)
        files = []
        self.fherr.write("Listing files...")
        for f in folders:
            files.extend(self.getFilesFromFolder(f))
        files.sort()
        return files
    
    def getFileFromRoot(self):
        root = f4sitem('root','/root','0','http://file4sharing.com/user/%s' % self._user)
        return self.getFilesFromFolder(root)
    
    def getFilesFromFolder(self, folder):
        '''
        TODO: deal with pages
        '''
        files = []
        folde_id  = folder.id
        page = 1
        while True:
            print 'page: %s'% page
            url = "http://file4sharing.com/?op=my_files&fld_id=%s&page=%s" % (folde_id, page) 
            self.fherr.write("Getting files from folder...%s" % folder.name)
            response = self.post_request(url)
            reFileEntity = re.compile('<TD><input type="checkbox" name="file_id" value="(?P<file_id>\d+)"></TD>.*?<TD align=left><a href="(?P<file_link>[^"]+)">(?P<file_name>.*?)</a></TD>', re.S|re.I)
            result_iter = reFileEntity.finditer(response)
            has_file_flag = False
            for r in result_iter:
                has_file_flag = True
                id = r.group("file_id")
                name = r.group("file_name")
                link = r.group("file_link")
                fsI = f4sitem(name,'file',id,link)
                files.append(fsI)
            if not has_file_flag:
                break
            page += 1
        files.sort()
        return files
    
    def getFolderList(self):   
        self.fherr.write("Getting folder list...") 
        foundFolders = []
        url = "http://file4sharing.com/?op=my_files"
        response = self.post_request(url)
        reFolder = re.compile('fld_id=(?P<folder_id>\d+)"><b>(?P<folder_name>.*?)</b></a></TD>')
        result_iter = reFolder.finditer(response)
        for r in result_iter:
            name = r.group('folder_name')
            id = r.group('folder_id')
            item = f4sitem(name, 'folder', id, 
                          'http://file4sharing.com/user/%s/%s/%s' % (self._user, id, name))
            foundFolders.append(item)
        foundFolders.sort()
        return foundFolders
    
    def find(self, filenames=[], filelist = None):
        '''
        open the filelist page according to opener with cookies
        '''
        found = []
        if filelist is None:
            filelist = self.getFileList()        
        filelistlower = [fl.name.lower() for fl in filelist]
        todel = []
        for fl in filenames:
            try:
                index = filelistlower.index(os.path.basename(fl).lower())
                found.append(filelist[index])
                todel.append(fl)
            except:
                continue
        for d in todel:
            filenames.remove(d)
        found.sort()
        return found

    def findFolder(self, foldername):        
        folders = self.getFolderList()
        for f in folders:
            if foldername == f.name:
                return f
        return None

    def createFolder(self, newfolder):
        foundfolder = self.findFolder(newfolder)
        if foundfolder is None:
            #f4s don't support subdir 
            return self.__newFolder(newfolder)
        self.fherr.write("Folder %s exsits." % newfolder)
        return foundfolder

    def __newFolder(self, newfolder, parentfolder=None):
        '''
        newfolder : without any '/',just a standard folder name
        '''
        print('Creating new folder: %s' % newfolder)
        data = {'op':'my_files',
                'fld_id':'0',
                'key':'',
                'create_new_folder':newfolder,
                'to_folder':''}
        url = "http://file4sharing.com/"
        self.post_request(url, data)  
        return self.findFolder(newfolder)
    
    def moveto(self, items, destFolder):
        if len(items) == 0:
            return
        print('Moving...')
        data =[]
        data.append(('op', 'my_files'))
        data.append(('fld_id', '0'))
        data.append(('key',''))
        data.append(('create_new_folder',''))
        data.append(('to_folder', destFolder.id))
        for item in items:
            data.append(('file_id', item.id))
        print data
        url = "http://file4sharing.com/"
        self.post_request(url, data)
        print('Moved.')
    
    def upload_web(self, file, progressLog=None, other_args=None):
        return self.upload_web_local(file, progressLog, other_args)
       
    def upload_web_local(self, file, progressLog=None, other_args=None):
        basefilename = os.path.basename(file)
        
        #get sess_id
        indexpage = self.post_request('http://file4sharing.com/').encode('utf8','ignore')
        re_sess_id = re.compile('name="sess_id" value="(?P<sess_id>[^"]+)"')
        s = re_sess_id.search(indexpage)
        if s is None:
            self.fherr.write("Fail to Get Upload Link for %s, Wait for 1min and Retry..." % file)
            return
        
        sess_id = s.group('sess_id')
        UID = random.randint(10000000000,999999999999)
        uploadlink = 'http://file4sharing.com/cgi-bin/upload.cgi?upload_id=%s&js_on=1&utype=reg&upload_type=file'\
                    % UID
                    
        data = {'upload_type':'file',
                'sess_id':sess_id,
                'srv_tmp_url':'http://file4sharing.com/tmp',
                'file_0':open(file,'rb'),
                'file_0_descr':'',
                'tos':'1',
                'submit_btn':'Upload!'}
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        result = self.post_file(uploadlink, \
                                  data, \
                                  self.get_cookies(), \
                                  callback=callback)
        s_pos = result.find("'fn'>")
        e_pos = result.find('<', s_pos)
        file_code = result[s_pos+5:e_pos]
        link = 'http://file4sharing.com/%s' % file_code
        
        #get file id
        data = {'fn':file_code,
                'st':'OK',
                'op':'upload_result'}
        id_page = self.post_request('http://file4sharing.com/', data)
        reID = re.compile('ic1-(?P<fild_id>\d+)')
        s = reID.search(id_page)
        file_id = 0
        if s is not None:
            file_id = s.group('fild_id')
            
        item = f4sitem(basefilename, 'file', file_id, link, self.rename_func(file))
        self.fherr.write(item.format())
        self.newupload.append(item)
        return item

if __name__ == "__main__":
    pass